import context from '../main.js';
//公共request
const fetch = {
  interfaceUrl: function () {
    // 接口地址
    // return "https://result.eolinker.com/xt3yEM61e5d8a3dc0e031805ff458eea566d227cdcac259";
    // return ''
	// return "http://fl.com";
	return "http://www.mqmflex.com";
  },
  toast: function (tips) {
    uni.showToast({
      title: tips || "Loading", //其实是error,为了不展示给用户
      icon: 'none',
      duration: 2000
    })
    setTimeout(function () {
      uni.hideToast();
    }, 2000);
  },
	/**
	 * url 请求url
	 * postData 请求数据
	 * method  POST or GET
	 * showLoading 请求结束前是否转菊花
	 * */
  request: function (url, postData, method, showLoading = true, hasToken = true) {
    //接口请求
    if (showLoading) {
      uni.showLoading({
        mask: true,
        title: context.$t('fetch.wait')
      })
    }
    let header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
    if (hasToken) {
      header.token = uni.getStorageSync("token") || ''
    }
    return new Promise((resolve, reject) => {
      uni.request({
        url: fetch.interfaceUrl() + url,
        data: postData,
        header: header,
        method: method,
        dataType: 'json',
        success: (res) => {
          showLoading && uni.hideLoading()
          if (res.data.code == '-2' || res.data.code === -2) {
            fetch.toast("please login")
            uni.removeStorage({
              key: 'token',
              success: function (res) {
                uni.navigateTo({
                  url: '/pages/login/index'
                });
              }
            });
            return
          } else if (res.data.code == 0 || res.data.code === '0') {
            resolve(res.data)
          } else if (res.data.code == -1 || res.data.code === '-1') {
            resolve(res.data)
          } else if (res.data.code == 1 || res.data.code === '1') {
            resolve(res.data)
          } else if (res.data.code == -3 || res.data.code === '-3') {
            resolve(res.data)
          } else {
            fetch.toast(res.data.msg)
            reject(res.data)
          }
        },
        fail: (res) => {
          // fetch.toast("请求失败")
          reject(res)
        }
      })
    })
  }
}

module.exports = {
  request: fetch.request,
  toast: fetch.toast,
  interfaceUrl: fetch.interfaceUrl
}
